package com.snapan.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private OSS ossClient;

    @Value("${oss.bucket-name}")
    private String bucketName;

    @Value("${oss.endpoint}") // 添加 endpoint 配置注入
    private String endpoint;

    @Value("${oss.domain:}")
    private String domain;

    @RequestMapping("/uploadFile")
    public void uploadFile(HttpServletRequest request, HttpServletResponse response,
                           String lastImage, String type) throws IOException {
        try {
            MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = mr.getFileMap();

            if (fileMap.isEmpty()) {
                response.getWriter().write(buildErrorJson("未选择文件"));
                return;
            }

            Set<String> keySet = fileMap.keySet();
            Iterator<String> iterator = keySet.iterator();
            String key = iterator.next();
            MultipartFile multipartFile = fileMap.get(key);

            // 获取原始文件名并生成新的唯一文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + suffix;

            if (StringUtils.isBlank(type)) {
                type = "avatar";
            }

            // 构建OSS中的文件路径
            String objectName = type + "/" + fileName;

            // 删除旧图片（如果存在）
            if (StringUtils.isNotBlank(lastImage)) {
                deleteOldImage(lastImage);
            }

            // 上传新图片到OSS
            try (InputStream inputStream = multipartFile.getInputStream()) {
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
                ossClient.putObject(putObjectRequest);
            }

            // 构建返回的URL - 使用注入的 endpoint
            String fileUrl;
            if (StringUtils.isNotBlank(domain)) {
                // 如果配置了自定义域名
                fileUrl = domain + "/" + objectName;
            } else {
                // 使用OSS默认域名
                fileUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            }

            JSONObject jo = new JSONObject();
            jo.put("realPath", fileUrl); // 完整URL
            jo.put("relativePath", objectName); // OSS中的相对路径
            jo.put("fileName", fileName);
            jo.put("code", 200);
            jo.put("message", "上传成功");

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jo.toString());

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write(buildErrorJson("上传失败：" + e.getMessage()));
        }
    }

    /**
     * 删除旧图片
     */
    private void deleteOldImage(String lastImage) {
        try {
            // 从lastImage中提取objectName
            String objectName = extractObjectNameFromUrl(lastImage);
            if (StringUtils.isNotBlank(objectName)) {
                ossClient.deleteObject(bucketName, objectName);
            }
        } catch (Exception e) {
            // 删除旧图片失败不影响新图片上传，只记录日志
            System.err.println("删除旧图片失败: " + e.getMessage());
        }
    }

    /**
     * 从URL中提取OSS objectName
     */
    private String extractObjectNameFromUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return null;
        }

        // 如果配置了自定义域名
        if (StringUtils.isNotBlank(domain) && url.startsWith(domain)) {
            return url.substring(domain.length() + 1);
        }

        // 如果是OSS默认域名格式
        String ossPrefix = "https://" + bucketName + ".";
        if (url.startsWith(ossPrefix)) {
            int startIndex = url.indexOf("/", ossPrefix.length());
            if (startIndex != -1) {
                return url.substring(startIndex + 1);
            }
        }

        // 如果已经是相对路径，直接返回
        return url;
    }

    private String buildErrorJson(String message) {
        JSONObject error = new JSONObject();
        error.put("code", 500);
        error.put("message", message);
        return error.toString();
    }
}